<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:11
 */

namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\ProjectCategory;
use think\Db;
use app\common\model\Minus as Minus_Model;
use app\common\model\Goods;
use app\common\model\Project;
use app\common\model\MinusItem;

class Minus extends Admin
{

    /**
     * 项目减免
     * @return mixed
     * @throws \think\Exception
     */
    public function index(){
        // 读取数据
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = Minus_Model::where($map)->order($order)->paginate();

        // 分页数据
        $page = $data_list->render();

        foreach ($data_list as $k=>$v)
        {
            $names = Minus_Model::alias('m')
                ->leftJoin('dp_qt_data_minus_item i','i.minus_id=m.id')
                ->leftJoin('dp_qt_project p','p.id=i.item_id')
                ->where(['i.minus_id'=>$v['id'],'i.source'=>1])
                ->column('i.name');

            $nameds = Minus_Model::alias('m')
                ->leftJoin('dp_qt_data_minus_item i','i.minus_id=m.id')
                ->leftJoin('dp_qt_project p','p.id=i.item_id')
                ->where(['i.minus_id'=>$v['id'],'i.source'=>2])
                ->column('i.name');

            //减免规则
            $data_list[$k]['rule'] = $v['type_ed']==1?'项目:'.$v['number'].'个':'金额:'.$v['money'];

            $data_list[$k]['type'] = $v['type']==1?'按项目':'按金额';

            $data_list[$k]['range'] = $v['range_start']&&$v['range_end']?intval($v['range_start']).'-'.intval($v['range_end']):'-';

            $data_list[$k]['project_name'] = implode(',',$names);

            $data_list[$k]['projected_name'] = implode(',',$nameds);

        }

        $btn_add = [
            'title' => '新增项目减免',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];

        $btn_edit = [
            'title' => '修改项目减免',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-info btn-sm',
            'href' => url('edit',['id'=>"__id__"]),
        ];

        $btn_item = [
            'title' => '添加减免的项目或者商品',
            'icon' => 'fa fa-fw fa-scribd',
            'class' => 'btn btn-info btn-sm',
            'href' => url('addItem',['id'=>"__id__"]),
        ];

        $btn_item_list = [
            'title' => '减免的项目或者商品列表',
            'icon' => 'fa fa-fw fa-sitemap',
            'class' => 'btn btn-info btn-sm',
            'href' => url('itemLists',['id'=>"__id__"]),
        ];

        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('sort', '序号', 'text')
            ->addColumn('name', '名称', 'text')
            ->addColumn('projected_name','被减免的项目')

            ->addColumn('rule', '减免的规则', 'text')
            ->addColumn('project_name','参与减免的项目','text')
            ->addColumn('type', '减免方式', 'text')
            ->addColumn('range', '减免方式', 'text')
            ->addColumn('right_button', '操作', 'btn')
            ->setTableName('qt_data_minus')// 指定数据表名
            ->addTopButton('add', $btn_add)// 添加顶部按钮
            ->addRightButton('edit', $btn_edit)// 添加顶部按钮
            ->addRightButton('item', $btn_item)// 添加顶部按钮
            ->addRightButton('lists', $btn_item_list)// 添加顶部按钮
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('减免项目列表')
            ->setRowList($data_list)// 设置表格数据
            ->setPages($page)// 设置分页数据
            ->fetch();
    }

    /**
     * 添加套餐
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            $result = $this->validate($data, 'Minus');

            if ($result!=true)$this->error($result);

            $info = Minus_Model::get(['name'=>$data['name']]);

            if ($info)$this->error('名称已经存在');

            if ($page = Minus_Model::create($data)) {

                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        } else {
            return ZBuilder::make('form')
                ->addText('sort', '', '', '', ['序号:',''])
                ->addText('name', '', '', '', ['名称:',''])
                ->addRadio('type_ed', '被减免方式', '', [1=>'按照项目',2=>'按照金额'])
                ->addText('amount', '', '', '', ['减免金额:',''])
                ->addText('number', '', '', '', ['共减免:','项目个数'])
                ->setTrigger('type_ed', 2, 'amount')
                ->setTrigger('type_ed', 1, 'number')

                ->addRadio('type', '减免方式', '', [1=>'按照项目',2=>'按照金额'])
                ->addText('range_start', '', '', '', ['减免消费要求区间下限:',''])
                ->addText('range_end', '', '', '', ['减免消费要求上限:',''])
                ->setTrigger('type', 2, 'range_start,range_end')
                ->addSelect('hand_card_type', '手牌方式', '', [1=>'消费手牌',2=>'男宾手牌',3=>'女宾手牌',4=>'儿童手牌',5=>'其他手牌',6=>'viper手牌'])
                ->addRadio('computer_type', '计算方式：', '', [1=>'按手牌计算单独计算',2=>'整单一起计算'])
                ->setPageTitle('添加减免')
                ->fetch();
        }
    }


    /**
     * 编辑套餐
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Minus');

            if (true !== $result) $this->error($result);


            if (Minus_Model::where('id',$id)->update($data)) {
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = Minus_Model::get($id);
            return ZBuilder::make('form')
                ->addText('sort', '', '', '', ['序号:',''])
                ->addText('name', '', '', '', ['名称:',''])
                ->addRadio('type_ed', '被减免方式', '', [1=>'按照项目',2=>'按照金额'])
                ->addText('amount', '', '', '', ['减免金额:',''])
                ->addText('number', '', '', '', ['共减免:','项目个数'])
                ->setTrigger('type_ed', 2, 'amount')
                ->setTrigger('type_ed', 1, 'number')

                ->addRadio('type', '减免方式', '', [1=>'按照项目',2=>'按照金额'])
                ->addText('range_start', '', '', '', ['减免消费要求区间下限:',''])
                ->addText('range_end', '', '', '', ['减免消费要求上限:',''])
                ->setTrigger('type', 2, 'range_start,range_end')
                ->addSelect('hand_card_type', '手牌方式', '', [1=>'消费手牌',2=>'男宾手牌',3=>'女宾手牌',4=>'儿童手牌',5=>'其他手牌',6=>'viper手牌'])
                ->addRadio('computer_type', '计算方式：', '', [1=>'按手牌计算单独计算',2=>'整单一起计算'])
                ->setPageTitle('添加减免')
                ->setFormData($info)
                ->fetch();
        }
    }

    /**
     * 添加减免的商品或者项目
     * @param null $id
     * @return mixed
     * @throws \think\Exception
     */
    public function addItem($id=null)
    {

        $goods_list = Goods::column('id,name');

        $project_list = Project::column('id,name');

        $goods_ids = MinusItem::alias('m')
            ->leftJoin('dp_qt_goods g','g.id=m.item_id')
            ->where(['m.source'=>2,'minus_id'=>$id,'item_type'=>'goods'])
            ->column('g.id');

        $project_ids = MinusItem::alias('m')
            ->leftJoin('dp_qt_project p','p.id=m.item_id')
            ->where(['m.source'=>2,'minus_id'=>$id,'item_type'=>'project'])
            ->column('p.id');

        if ($this->request->isPost())
        {
            $data = $this->request->post();

            if (count($data['goods_id'])>0)
            {
                foreach ($data['goods_id'] as $v)
                {
                    if (!in_array($v,$goods_ids))
                    {
                        $goods_info = Goods::get($v);

                        $result = MinusItem::create([
                            'minus_id'=>$data['minus_id'],
                            'item_id'=>$v,
                            'item_type'=>'goods',
                            'name'=>$goods_info['name'],
                            'price'=>$goods_info['price'],
                            'source'=>$data['source']
                        ]);
                    }
                }
            }

            if (count($data['project_id'])>0)
            {
                foreach ($data['project_id'] as $v)
                {
                    if (!in_array($v,$project_ids))
                    {
                        $project_info = Project::get($v);

                        $result = MinusItem::create([
                            'minus_id'=>$data['minus_id'],
                            'item_id'=>$v,
                            'item_type'=>'project',
                            'name'=>$project_info['name'],
                            'price'=>$project_info['price'],
                            'source'=>$data['source']
                        ]);
                    }
                }
            }

            $result?$this->success('操作成功','index'):$this->error('操作失败');

        }

        return ZBuilder::make('form')
            ->addHidden('minus_id',$id)
            ->addRadio('source','请选择类型','',[1=>'减免',2=>'被减免'])
            ->addSelect('goods_id', '请选择商品', '', $goods_list,'','multiple')
            ->addSelect('project_id', '请选择项目', '', $project_list,'','multiple')
            ->setFormData()
            ->setPageTitle('编辑项目')
            ->fetch();
    }

    /**
     * 包含的项目或者商品列表
     * @param $id
     * @return mixed
     * @throws \think\Exception
     */
    public function itemLists($id)
    {
        $list = MinusItem::where('minus_id',$id)->select();

        foreach ($list as $k=>$v)
        {
            if ($v['item_type']=='goods')
            {
                $list[$k]['name'] = $v['name'].'/商品';
            }elseif ($v['item_type']=='project')
            {
                $list[$k]['name'] = $v['name'].'/项目';

            }
        }


        //设置页面
        return ZBuilder::make('table')
            ->addColumn('id', 'ID', 'text')
            ->addColumn('name', '套餐名称', 'text')
            ->addColumn('price', '项目价格', 'text')
            ->addColumn('source','类型','status','',[1=>'减免:success',2=>'被减免:info'])
            ->setTableName('qt_data_minus_item')// 指定数据表名
            ->addTopButton('delete')
            ->setPrimaryKey('id')// 设置主键名为username
            ->setPageTitle('减免的商品或者列表')
            ->setRowList($list)// 设置表格数据
            ->fetch();
    }

    /**
     * 删除套餐里包含的项目或者商品
     * @param $id
     */
    public function delItem($id)
    {

        if ( MinusItem::destroy($id))
        {
            $this->success('操作成功','index');
        }else{
            $this->error('删除失败');
        }
    }

}